package com.ifast.face.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ifast.common.utils.Result;
import com.ifast.face.dao.UserFaceInfoDao;
import com.ifast.face.domain.UserFaceInfo;
import com.ifast.face.dto.ProcessInfo;
import com.ifast.face.service.FaceEngineService;
import com.ifast.face.service.UserFaceInfoService;
import com.ifast.face.util.ImageInfo;
import com.ifast.face.util.ImageUtil;
import com.ifast.face.util.WorkId;
import com.xiaoleilu.hutool.date.DateUtil;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import net.coobird.thumbnailator.Thumbnails;


@Service("userFaceInfoService")
public class UserFaceInfoServiceImpl extends ServiceImpl<UserFaceInfoDao, UserFaceInfo> implements UserFaceInfoService {
  
	 
	@Autowired
    private FaceEngineService faceEngineService; 
    
    @Override
    public List<UserFaceInfo> findByFaceIds(List<String> faceIds){
    	if(CollectionUtil.isEmpty(faceIds)){
    		return null;
    	}
        return baseMapper.findByFaceId(faceIds);
    }
    

	@Override
	public UserFaceInfo saveFace(UserFaceInfo userFaceInfo) {
		baseMapper.insert(userFaceInfo);
		return userFaceInfo;
	}
	
	@Override
    public void deleteInBatch(List<UserFaceInfo> users){ 
		baseMapper.deleteBatchIds(users.stream().map(user -> user.getId()).collect(Collectors.toList()));
    }
	
	@Override
	public IPage<UserFaceInfo> selectPage(Page<UserFaceInfo> page){
		IPage<UserFaceInfo> users = super.page(page);
		users.getRecords().stream().forEach(user -> {user.setGenderName((new Integer(1)).equals(user.getGender())?"男":"女");
		user.setCheckState((new Integer(1)).equals(user.getChecked())?"已检测到":"未检测到");});
		return users;
	} 
    @Override
	public IPage<UserFaceInfo> selectPage(Page<UserFaceInfo> page, Wrapper<UserFaceInfo> wrapper) {
    	IPage<UserFaceInfo> users = super.page(page, wrapper);
    	users.getRecords().stream().forEach(user -> {user.setGenderName((new Integer(1)).equals(user.getGender())?"男":"女");
		user.setCheckState((new Integer(1)).equals(user.getChecked())?"已检测到":"未检测到");});
		return users;
	}


	@Override
	public Result<?> add(HttpServletRequest request, UserFaceInfo user) throws Exception {
		 
		MultipartFile file = getFirstFile(request); 
		if(file == null){
			return Result.fail("请上传照片");
		}
		user = file2Base64(file,user);
		if(user.getFaceFeature() == null){
			return Result.fail("请上含有一张人脸的照片");
		}
        String faceId = WorkId.sortUID(); 
        //人脸特征插入到数据库
        baseMapper.insert(user.setChecked(0).setCreateTime(DateUtil.now()).setFaceId(faceId)); 
        //人脸信息添加到缓存
        faceEngineService.refresh(user.getGroupId());
		return Result.ok();
	}
	@Override
	public Result<?> update(HttpServletRequest request, UserFaceInfo user) throws Exception {
		UserFaceInfo oldUser = this.baseMapper.selectById(user.getId());
		if(oldUser == null){
			return Result.fail("编辑的数据不存在");
		} 
		MultipartFile file = getFirstFile(request);
		if(file != null){
			oldUser = file2Base64(file,oldUser);
		} 
		oldUser.setName(user.getName())
			.setAge(user.getAge())
			.setGender(user.getGender())
			.setGroupId(user.getGroupId())
			.setUpdateId(user.getUpdateId())
			.setUpdateTime(DateUtil.now()); 
		baseMapper.updateById(oldUser);
		 //人脸信息添加到缓存
        faceEngineService.refresh(user.getGroupId());
		return Result.ok();
	}
	
	private UserFaceInfo file2Base64(MultipartFile file,UserFaceInfo user){
		try(InputStream inputStream = file.getInputStream();
				ByteArrayOutputStream stream2 = new ByteArrayOutputStream();){
			
	        BufferedImage bufImage = ImageIO.read(inputStream);
	        ImageInfo imageInfo = ImageUtil.bufferedImage2ImageInfo(bufImage); 
	        //人脸特征获取
	        List<ProcessInfo> process = faceEngineService.extractFaceFeature(imageInfo);  
	        if (CollectionUtils.isEmpty(process)) {
	        	return user;
	        } 
	        byte[] bytes = process.get(0).getFaceFeature().getFeatureData();
	        user.setFaceFeature(bytes);
	        Thumbnails.of(bufImage).scale(0.5).outputFormat("jpg").toOutputStream(stream2);
			user.setImgPath("data:image/jpeg;base64,"+Base64.encode(stream2.toByteArray())); 
		} catch (Exception e) {
			 e.printStackTrace();
		}
		return user;
	} 
	
	private MultipartFile getFirstFile(HttpServletRequest request){
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext()); 
		MultipartFile file = null;
		if (multipartResolver.isMultipart(request)) {
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				file = multiRequest.getFile(iter.next()); 
				if (file != null) {
					break;
				} 
			}
		}
		return file;
	}
}
